﻿using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using WebDocDB.DocumentDBManager;
using WebDocDB.Managers;
using WebDocDB.Models;

namespace WebDocDB.Controllers
{
    public class DatabasesController : Controller
    {
        private IAccountManager accountManager;
        private IDatabasesManager databaseManager;

        public DatabasesController(IAccountManager accountManager, IDatabasesManager databaseManager)
        {
            this.accountManager = accountManager;
            this.databaseManager = databaseManager;
        }

        // GET: Databases
        public async Task<ActionResult> Index()
        {
            if (accountManager.GetAccountSettings() != null)
            {               
                var databases = await databaseManager.GetAllDatabases();
                return View(databases.OrderBy(db => db.ID).ToList());
            }

            return RedirectToAction("Index", "Home");
        }

        // GET: Databases/Create
        public ActionResult Create()
        {
            var dbModel = new Models.Database();
            return PartialView("_Create", dbModel);
        }

        // POST: Databases/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
        public async Task<JsonResult> Create(Models.Database dbModel)
        {
            if (ModelState.IsValid)
            {
                if (accountManager.GetAccountSettings() != null)
                {
                    try
                    {                        
                        await databaseManager.AddDatabase(dbModel.ID);
                        return Json(new AjaxResponse() { Success = true });
                    }
                    catch (Exception ex)
                    {
                        return Json(new AjaxResponse() { Success = false, Message = ex.Message });
                    }

                }
            }

            return Json(new AjaxResponse() { Success = false, Message = "Invalid data" });
        }  

        [HttpPost]
        public async Task<ActionResult> Delete(string databaseLink)
        {
            if (accountManager.GetAccountSettings() != null)
            {                
                try
                {                    
                    await databaseManager.DeleteDatabase(databaseLink);
                    return Json(new AjaxResponse() { Success = true });
                }
                catch (Exception ex)
                {
                    return Json(new AjaxResponse() { Success = false, Message = ex.Message });
                }
            }

            return RedirectToAction("Index", "Home");
        }
    }
}